package com.sskj.market.ui.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.CopyUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.market.R;
import com.sskj.market.R2;
import com.sskj.market.bean.OrderBuyBean;
import com.sskj.market.bean.ShopDetailsBean;
import com.sskj.market.component.DaggerUserDataComponent;
import com.sskj.market.http.HttpConfig;
import com.sskj.market.presenter.CommodityDetailsPresenter;
import com.sskj.market.util.GlideUtils;
import com.sskj.market.view.MarketMoreAndLessView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Hey
 * Create at  2019/07/25
 */
@Route(path = RConfig.MARKET_ACTIVITY_COMMODITY_DETAILS)
public class CommodityDetailsActivity extends BaseActivity<CommodityDetailsPresenter> {

    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.tvKeFu)
    TextView tvKeFu;
    @BindView(R2.id.recycle_mall_details)
    RecyclerView recycleMallDetails;
    @BindView(R2.id.btStartBuy)
    Button btStartBuy;
    @BindView(R2.id.tvReturn)
    TextView tvReturn;
    @Inject
    UserViewModel userViewModel;
    UserData userData;
    private boolean isSuperUser=false;

    private MallDetailsAdapter addItemDecoration;
    private ViewHolder headerHolder;
    @Autowired
    int product_id;
    private OrderBuyBean buyBean;
    List<String> picDetails = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.market_activity_commodity_details;
    }

    @Override
    public CommodityDetailsPresenter getPresenter() {
        return new CommodityDetailsPresenter();
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        ARouter.getInstance().inject(this);
        mPresenter.getShopDetails(product_id, true);
        tvTitle.setText(App.INSTANCE.getString(R.string.market_commodityDetailsActivity1));
        tvReturn.setVisibility(View.VISIBLE);
        ClickUtil.click(300, tvKeFu, () -> mPresenter.getServices(mPresenter));
        recycleMallDetails.setLayoutManager(new LinearLayoutManager(this));
        addItemDecoration = new MallDetailsAdapter(picDetails);
        View view = LayoutInflater.from(this)
                .inflate(R.layout.market_item_header_commodity, null);
        headerHolder = new ViewHolder(view);
        addItemDecoration.addHeaderView(view);
        View footer = LayoutInflater.from(this).inflate(R.layout.market_footer, null);
        addItemDecoration.addFooterView(footer);
        addItemDecoration.bindToRecyclerView(recycleMallDetails);


    }

    @Override
    protected void onStart() {
        super.onStart();
        headerHolder.bannerMarketHeader.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        headerHolder.bannerMarketHeader.stopAutoPlay();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                if (userData.getSuper_user() != 1) {
                    isSuperUser=true;
                }
            } else {
                userData = null;
            }
        });


        headerHolder.marketMoreAndLessView.setLessAndMoreCallBack(new MarketMoreAndLessView.LessAndMoreCallBack() {
            @Override
            public void addCallBack(int current) {
            }

            @Override
            public void deleteCallBack(int current) {
            }

            @Override
            public void outOfValueCallBack(String msg) {
                ToastUtil.showShort(msg);
            }

            @Override
            public void valueChangeCallBack(int current) {
                buyBean.setAllCount(String.valueOf(current));
            }
        });

        ClickUtil.click(300, btStartBuy, () -> {
            if (isSuperUser){
                onBuySuperPlatform();
                return;
            }
            if (!AppCircleCheckUtil.checkLogin(this, userData)) {
                return;
            }

            if (buyBean == null) {
                return;
            }
            String empty = "0";
            if (empty.equals(buyBean.getAllCount())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.market_commodityDetailsActivity3));
                return;
            }
            double all = headerHolder.marketMoreAndLessView.getCurrentValue() * Double.parseDouble(buyBean.getGoodsPrice()) +
                    Double.parseDouble(buyBean.getExpressPrice());
            buyBean.setAllPrice(NumberUtil.keep(String.valueOf(all), 2));

            Intent intent = new Intent(CommodityDetailsActivity.this, SubmitOrderActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("goodsInfo", buyBean);
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
        });


    }

    private void onBuySuperPlatform() {
        View view = LayoutInflater.from(this)
                .inflate(R.layout.lib_bug_super_dialog, null);
        Dialog dialog = new Dialog(this, R.style.market_bottom_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        SuperHolder kfViewHolder = new SuperHolder(view);
        ClickUtil.click(kfViewHolder.tvDialogCancel, dialog::dismiss);
        ClickUtil.click(kfViewHolder.tvDialogSure, () -> {
            ARouter.getInstance().build(RConfig.SUPER_PLATFORM).withBoolean("isSuper",true).navigation();
            dialog.dismiss();
        });
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = getWindowManager().getDefaultDisplay().getWidth() - 60;
        view.setLayoutParams(layoutParams);
        Objects.requireNonNull(dialog.getWindow()).setGravity(Gravity.CENTER);
        dialog.getWindow().setWindowAnimations(R.style.market_pop_show_style);
        dialog.show();
    }

    @Override
    public void initData() {

    }


    public void getKeFuSuccess(String services) {
        showKfDialog(services);
    }


    @SuppressLint("SetTextI18n")
    private void showKfDialog(String msg) {
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(this)
                .inflate(R.layout.lib_contact_item, null);
        Dialog dialog = new Dialog(this, R.style.market_bottom_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        KfViewHolder kfViewHolder = new KfViewHolder(view);
        kfViewHolder.tvKfLib.setText(msg);
        ClickUtil.click(kfViewHolder.btCancel, dialog::dismiss);
        ClickUtil.click(kfViewHolder.btSure, () -> {
            CopyUtil.copy(kfViewHolder.tvKfLib.getText().toString());
            dialog.dismiss();
        });
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = getWindowManager().getDefaultDisplay().getWidth() - 60;
        view.setLayoutParams(layoutParams);
        Objects.requireNonNull(dialog.getWindow()).setGravity(Gravity.CENTER);
        dialog.getWindow().setWindowAnimations(R.style.market_pop_show_style);
        dialog.show();
    }

    @SuppressLint("SetTextI18n")
    public void getShopDetailsSuccess(ShopDetailsBean data) {
        if (data == null) {
            return;
        }
        if (data.getPics().size() != 0) {
            buyBean = new OrderBuyBean(data.getId() + "", data.getPics().get(0), data.getName(), data.getPrice());
        }
        buyBean.setExpressPrice(data.getShipping_money());
        headerHolder.bannerMarketHeader.setImages(data.getPics())
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        imageView.setAdjustViewBounds(true);
                        imageView.setMaxHeight(10000000);
                        Glide.with(CommodityDetailsActivity.this)
                                .load(HttpConfig.BASE_IMG_URL + path)
                                .apply(RequestOptions.errorOf(R.drawable.no_banner)
                                        .placeholder(R.drawable.no_banner))
                                .into(imageView);
                    }
                })
                .setBannerStyle(BannerConfig.NUM_INDICATOR)
                .setDelayTime(3500)
                .start();

        headerHolder.nameMarketHeader.setText(data.getName());
        headerHolder.desMarketHeader.setText(data.getGoods_desc());
        headerHolder.priceMarketHeader.setText(data.getPrice() + "LAC");
        headerHolder.kcMarketHeader.setText(App.INSTANCE.getString(R.string.market_commodityDetailsActivity4) + data.getNum() + App.INSTANCE.getString(R.string.market_commodityDetailsActivity5));
        headerHolder.payMarketHeader.setText(data.getPurchase_number() + App.INSTANCE.getString(R.string.market_shoppingActivity2));
        headerHolder.marketMoreAndLessView.setMaxCount(Integer.parseInt(data.getNum()));
        headerHolder.marketMoreAndLessView.setValue(Integer.parseInt(data.getNum()) == 0 ? 0 : 1);
        buyBean.setAllCount(String.valueOf(headerHolder.marketMoreAndLessView.getCurrentValue()));
        addItemDecoration.setNewData(data.getDesc());
        addItemDecoration.notifyDataSetChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    class MallDetailsAdapter extends BaseQuickAdapter<String, BaseViewHolder> {


        private MallDetailsAdapter(@Nullable List<String> data) {
            super(R.layout.market_shop_details_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            ImageView ivShopDetailsItem = helper.getView(R.id.ivShopDetailsItem);
            GlideUtils.Show(item, ivShopDetailsItem);
        }
    }

    class ViewHolder {
        @BindView(R2.id.banner_market_header)
        Banner bannerMarketHeader;
        @BindView(R2.id.name_market_header)
        TextView nameMarketHeader;
        @BindView(R2.id.des_market_header)
        TextView desMarketHeader;
        @BindView(R2.id.price_market_header)
        TextView priceMarketHeader;
        @BindView(R2.id.kc_market_header)
        TextView kcMarketHeader;
        @BindView(R2.id.pay_market_header)
        TextView payMarketHeader;
        @BindView(R2.id.count_market_header)
        TextView countMarketHeader;
        @BindView(R2.id.mare_less_market_header)
        MarketMoreAndLessView marketMoreAndLessView;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    class KfViewHolder {
        @BindView(R2.id.tv_kf_lib)
        TextView tvKfLib;
        @BindView(R2.id.btCancel)
        Button btCancel;
        @BindView(R2.id.btSure)
        Button btSure;

        KfViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    class SuperHolder {
        @BindView(R2.id.tvDialogTitle)
        TextView tvDialogTitle;
        @BindView(R2.id.tvDialogCancel)
        TextView tvDialogCancel;
        @BindView(R2.id.tvDialogSure)
        TextView tvDialogSure;

        SuperHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
